﻿<!DOCTYPE html>
<html>
<body>
  <img src="webworker.jpg"></img>
  <div>
    <button id="invert">逆色</button>
    <button id="grayscale">黑白</button>
  </div>
  <canvas width=550 height=100 style="border:1px solid black"></canvas>
</body>
<script type="text/javascript">
var worker = new Worker('webworker.js');             // 实例化Web Workers对象，传递脚本
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var buttons = document.querySelectorAll('button');
var img = document.querySelector('img');
worker.addEventListener('message', function(e) {      // 监听worker 的message事件，接收返回信息
   context.putImageData(e.data, 0, 0);
}, false);
for(var i =0; buttons[i]; i++){
  buttons[i].addEventListener('click',function(e){
    e.preventDefault();
    context.drawImage(img,0,0);
    var imgData = context.getImageData(0,0,img.width,img.height);
    worker.postMessage({ id : this.id, data : imgData});
  });
};
</script>
</html>